package com.project.hqshorttaxi.filter;

import com.alibaba.fastjson.JSON;
import com.project.hqshorttaxi.entity.Login;
import com.project.hqshorttaxi.service.LoginService;
import com.project.hqshorttaxi.util.RestResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Calendar;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)) {
            response.setContentType("text/json; charset=utf-8");
            RestResult result = RestResult.error(500,"请求头部未包含token",null);
            PrintWriter writer = response.getWriter();
            writer.print(JSON.toJSON(result));
            return false;
        } else {
            // 验证token有效性
            Login entity = loginService.getByToken(token);
            if (entity == null) {
                response.setContentType("text/json; charset=utf-8");
                RestResult result = RestResult.error(500,"token不正确",null);
                PrintWriter writer = response.getWriter();
                writer.print(JSON.toJSON(result));
                return false;
            } else {
                Calendar calendar = Calendar.getInstance();
                long now = calendar.getTime().getTime();
                if (now > entity.getExpirationDate().getTime()) {
                    response.setContentType("text/json; charset=utf-8");
                    RestResult result = RestResult.error(500,"token已过期,请重新登录",null);
                    PrintWriter writer = response.getWriter();
                    writer.print(JSON.toJSON(result));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
